import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/Index.vue'
import UserCenter from '../views/inc/UserCenter.vue'
import store from '../store'

import axios from "axios"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/userCenter',
        name: 'UserCenter',
        meta: {
          title: '个人中心'
        },
        component: UserCenter
      },
      {
        path: '/index',
        name: 'Index',
        meta: {
          title: '首页',
          icon: "el-icon-s-home"
        },
        component: Index
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue')
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  let hasRoute = store.state.menus.hasRoute
  let token = store.state.token
  console.log("路由守卫正常运行," + "是否已经配置路由：" + store.state.menus.hasRoute)
  console.log("from路径：" + from.path)
  console.log("to路径：" + to.path)
  if (to.path == '/login') {
    next()
  } else if (!token) {
    next('/login')
  } else if (!hasRoute && token) {
    console.log("初始化菜单信息、标题信息和路由信息")
    let newRoutes = router.options.routes;
    axios.post("/menu/nav", null, {
      headers: {
        'authorization': token
      }
    }).then(res => {
      // console.log(res.data.data)
      store.commit("setMenuList", res.data.data.nav)
      store.commit("setPermList", res.data.data.authorities)
      res.data.data.nav.forEach(menu => {
        if (menu.children) {
          menu.children.forEach(item => {
            //转成路由
            let route = menuToRoute(item)
            //把路由添加路由管理中
            if (route) {
              newRoutes[0].children.push(route)
            }
          })
        }
      })
      store.state.menus.hasRoute = true
      router.matcher = new VueRouter(
        {
          mode: 'history',
          base: process.env.BASE_URL,
        }
      ).matcher // reset router
      newRoutes.forEach(newRoute => {
        router.addRoute(newRoute)
      })
      // router.addRoutes(newRoutes)
      next()
    })
  } else if (to.path == '/' || to.path == '') {
    next({ path: "/index" })
  } else if (to.path === "/userCenter") {
    // console.log(to)
    let obj = {
      name: to.name,
      title: to.meta.title,
    };
    store.commit("addTab", obj);
  }
  next()
})
const menuToRoute = (menu) => {
  if (menu.component) {
    let route = {
      name: menu.name,
      meta: {
        title: menu.title,
        icon: menu.icon
      },
      path: menu.path,
      component: () => import('@/views/' + menu.component + '.vue')
    }
    // console.log(route)
    return route
  }
  else return null
}
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
// 解决思路：对Router原型链上的push、replace方法进行重写，这样就不用每次调用方法都要加上catch。
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

export default router
